// class Cart{
//   constructor(){
//     this.getCartGoods();
//     this.$('.cart-list').addEventListener('click',this.dispatch)
//   }
//   dispatch=(eve)=>{
//     // console.log(this);
//     let target=eve.target;
//     // console.log(target);
//     if(target.nodeName =='A' && target.classList.contains('del1')) this.delGoodsData(target)
//   }
//   delGoodsData(tar){
//      console.log(tar);
//     let id=tar.parentNode.parentNode.parentNode.dataset.id;
//     console.log(id);
//   }
// async getCartGoods(){
//   const AUTH_TOKEN=localStorage.getItem('token')

//   axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
//   let {data,status}=await axios.get('http://localhost:8888/cart/list',{
//    params:{
//     id:localStorage.getItem('user_id')
//    }

//   })
//     // console.log(res);
//     if(status == 200 && data.code == 1){
//       // console.log(data.cart);
//       let html='';
//       data.cart.forEach(goods => {
//         // console.log(goods);

//         html += `<ul class="goods-list yui3-g" data-id="${goods.goods_id}">
//         <li class="yui3-u-3-8 pr">
//             <input type="checkbox" class="good-checkbox">
//             <div class="good-item">
//                 <div class="item-img">
//                     <img src="${goods.img_small_logo}">
//                 </div>
//                 <div class="item-msg">${goods.title}</div>
//             </div>
//         </li>
//         <li class="yui3-u-1-8">
            
//         </li>
//         <li class="yui3-u-1-8">
//             <span class="price">${goods.current_price}</span>
//         </li>
//         <li class="yui3-u-1-8">
//             <div class="clearfix">
//                 <a href="javascript:;" class="increment mins">-</a>
//                 <input autocomplete="off" type="text" value="${goods.cart_number}" minnum="1" class="itxt">
//                 <a href="javascript:;" class="increment plus">+</a>
//             </div>
//             <div class="youhuo">有货</div>
//         </li>
//         <li class="yui3-u-1-8">
//             <span class="sum">${goods.current_price * goods.cart_number}</span>
//         </li>
//         <li class="yui3-u-1-8">
//             <div class="del1">
//                 <a href="javascript:;">删除</a>
//             </div>
//             <div>移到我的关注</div>
//         </li>
//     </ul>`;
//       });
//       //将拼接好的字符串追加到页面中
//       this.$('.cart-list').innerHTML += html;
//     }
  
// }
// $(ele) {
//   let res = document.querySelectorAll(ele);
//   return res.length == 1 ? res[0] : res;
// }
// }
// new Cart;



class cart {
  constructor() {
    this.checkLogin();
    this.getCartGoods();
    this.bindEve();
  }
  bindEve() {
    this.$('.cart-list').addEventListener('click', this.distributeEve.bind(this));
    this.$('.cart-th input').addEventListener('click', this.clickAllChecked.bind(this))
  }
  async checkLogin() {
    const TOKEN = localStorage.getItem('token');
    axios.defaults.headers.common['authorization'] = TOKEN;
    let userId = localStorage.getItem('user_id');
    let { data, status } = await axios.get('http://localhost:8888/users/info/' + userId);
    // console.log(data);
    if (!TOKEN || data.code == 401) {
      location.assign('./login.html?ReturnUrl=./cart.html')
    }
  }
  async getCartGoods() {//获取购物车中的数据
    const TOKEN = localStorage.getItem('token');
    let userId = localStorage.getItem('user_id');
    axios.defaults.headers.common['authorization'] = TOKEN;
    let { data, status } = await axios.get('http://localhost:8888/cart/list?id=' + userId);
    if (status == 200) {
      if (data.code == 401) location.assign('./login.html?ReturnUrl=./cart.html')
      if (data.code == 1) {
        let html = '';
        // console.log(data.cart);
        data.cart.forEach(goods => {
          html += `<ul data-id="${goods.goods_id}" class="goods-list yui3-g">
          <li class="yui3-u-3-8 pr">
              <input type="checkbox" class="good-checkbox">
              <div class="good-item">
                  <div class="item-img">
                      <img src="${goods.img_small_logo}">
                  </div>
                  <div class="item-msg">${goods.title}</div>
              </div>
          </li>
          <li class="yui3-u-1-8">
             
          </li>
          <li class="yui3-u-1-8">
              <span class="price">${goods.price}</span>
          </li>
          <li class="yui3-u-1-8">
              <div class="clearfix">
                  <a href="javascript:;" class="increment mins">-</a>
                  <input autocomplete="off" type="text" value="${goods.cart_number}" minnum="1" class="itxt">
                  <a href="javascript:;" class="increment plus">+</a>
              </div>
              <div class="youhuo">有货</div>
          </li>
          <li class="yui3-u-1-8">
              <span class="sum">${goods.price * goods.cart_number}</span>
          </li>
          <li class="yui3-u-1-8">
              <div class="del1">
                  <a href="javascript:;">删除</a>
              </div>
              <div>移到我的关注</div>
          </li>
      </ul>`;
        });
        this.$('.cart-list').innerHTML = html;
      }
    }
  }
  distributeEve({ target }) {
    if (target.parentNode.classList.contains('del1')) {

      this.delGoods(target);

    }
    if (target.classList.contains('good-checkbox')) {
      this.getOneGoodsCheck(target);
      this.getNumPriceGoods()
    }
  }
  delGoods(target) {
    let that = this;   
    let layerIndex = layer.confirm('确认删除?', {
      title: '删除提示'
    }, function () {
      // console.log('888');
      let ulObj = target.parentNode.parentNode.parentNode;
      // console.log(ulObj);
      let id = ulObj.dataset.id;
      // console.log(id);
      let userId = localStorage.getItem('user_id');
      // console.log(id,userId);
      axios.get('http://localhost:8888/cart/remove?id=' + userId + '&goodsId=' + id)
        .then(res => {
          let { data, status } = res;
          // console.log(data,status);
          if (data.code == 1) {  
            layer.close(layerIndex);
            layer.msg('商品删除成功');
            ulObj.remove();
            that.getNumPriceGoods()
          }

        });
    })
  }
  getOneGoodsCheck(target) {
    // console.log(target.checked);
    if (!target.checked) {
      this.$('.cart-th input').checked = false;
      return;
    }
    if (target.checked) {
      let res = Array.from(this.$('.good-checkbox')).find(checkbox => {
        // console.log(checkbox.checked);
        return !checkbox.checked

      });
      // console.log(res);
      if (!res) this.$('.cart-th input').checked = true;
    }
  }
  getNumPriceGoods() {
    let goods = document.querySelectorAll('.goods-list');
  //  console.log(goods);
    let totalNum = 0;
    let totalPrice = 0;
    goods.forEach(one => {
      if (one.firstElementChild.firstElementChild.checked) {
        // console.log(one);
        totalNum = one.querySelector('.itxt').value - 0 + totalNum;
        totalPrice = one.querySelector('.sum').innerHTML - 0 + totalPrice;
      }

    });
    // console.log(totalNum,totalPrice);
    this.$('.sumprice-top strong').innerHTML = totalNum;
    this.$('.sumprice-top .summoney').innerHTML = totalPrice;
  }
  clickAllChecked(eve) {
    // console.log(eve.target);
    let checked = eve.target.checked;
    // console.log(checked);
    this.oneGoodsCheck(checked);
    this.getNumPriceGoods();
  }
  oneGoodsCheck(checkStatus) {
    let goodsList = this.$('.goods-list');
    // console.log(goodsList,checkStatus);
    goodsList.forEach(ul => {
      // console.log(ul);
      ul.firstElementChild.firstElementChild.checked = checkStatus;
    })
  }
  $(tag) {
    let res = document.querySelectorAll(tag)
    return res.length == 1 ? res[0] : res;
  }
}
new cart();